package concurrency.deadlock;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class FixedDiningPhilosophers {
    public static void main(String[] args) throws Exception {
        int ponder = 0;//死锁的参数，值越小越倾向于发生死锁。不能小于0
        int size = 5;
        ExecutorService exec = Executors.newCachedThreadPool();
        Chopstick[] sticks = new Chopstick[size];
        for (int i = 0; i < size; i++)
            sticks[i] = new Chopstick();
        /*
         * Philosopher 0 -- left:0,right:1
         * Philosopher 1 -- left:1,right:2
         * Philosopher 2 -- left:2,right:3
         * Philosopher 3 -- left:3,right:4
         * Philosopher 4 -- left:0,right:4
         * */
        for (int i = 0; i < size; i++){
            if (i < (size - 1)){
                exec.execute(new Philosopher(sticks[i], sticks[i + 1], i, ponder));
            }else{
                exec.execute(new Philosopher(sticks[0], sticks[i], i, ponder));
            }
        }
        System.out.println("Press ‘Enter’ to quit");
        System.in.read();
        exec.shutdownNow();
    }
}
